package com.medvalley.tcm.controller;

import com.aliyuncs.exceptions.ClientException;
import com.medvalley.tcm.base.Result;
import com.medvalley.tcm.domain.UserInfo;
import com.medvalley.tcm.domain.UserInfoDetail;
import com.medvalley.tcm.service.SMSService;
import com.medvalley.tcm.service.UserInfoService;
import com.medvalley.tcm.service.impl.AliOSSService;
import com.medvalley.tcm.vo.outputvo.UserConfigOutputVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Api(value = "APP用户相关接口")
public class UserController extends BaseController {

    private static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Value("${oss.headicon.bucketName}")
    private String headIconBucketName;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private SMSService smsService;

    @Autowired
    private AliOSSService aliOSSService;

    @ApiOperation(value = "发送短信验证码")
    @RequestMapping(value = "/smscode/get", method = RequestMethod.POST)
    public Result getSmsCode(@RequestParam String phone) throws ClientException {
        smsService.sendSmsCode(phone);
        return success("短信验证码已发送");
    }

    @ApiOperation(value = "注册")
    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public Result validateSmsCode(@RequestParam String phone, @RequestParam String smsCode, @RequestParam String password) {
        boolean result = smsService.validateCode(phone, smsCode);
        if (result) {
            Result r = userInfoService.register(phone, password);
            return r;
        } else {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("status", 3);
            resultMap.put("message", "验证码错误");
            return error("验证码错误", resultMap);
        }
    }

    @ApiOperation(value = "短信验证码登录")
    @RequestMapping(value = "/login/smscode", method = RequestMethod.POST)
    public Result login(@RequestParam String phone, @RequestParam String smsCode) {
        boolean isSmsCodeRight = smsService.validateCode(phone, smsCode);
        if (!isSmsCodeRight) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("status", 3);
            resultMap.put("message", "验证码错误");
            return error("验证码错误", resultMap);
        }
        Result result = userInfoService.loginBySmsCode(phone);
        return result;
    }

    @ApiOperation(value = "用户名密码登录")
    @RequestMapping(value = "/login/password", method = RequestMethod.POST)
    public Result loginPassword(@RequestParam String phone, @RequestParam String password) {
        Result result = userInfoService.loginByPassword(phone, password);
        return success(result);
    }


    @ApiOperation(value = "退出登录")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result logout(@RequestParam String phone, HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        if (sessionPhone.equals(phone)) {
            userInfoService.logout(getToken(request));
            return success();
        } else {
            return error(" 请确认是本人操作");
        }
    }

    @ApiOperation(value = "展示个人信息")
    @RequestMapping(value = "/info/get", method = RequestMethod.POST)
    public Result getUserInfoDetail(HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        UserInfoDetail userInfoDetail = userInfoService.getUserInfoDetail(sessionPhone);
        return success("", userInfoDetail);
    }


    /**
     * 编辑个人资料
     */
    @ApiOperation(value = "编辑个人信息")
    @RequestMapping(value = "/info/edit", method = RequestMethod.POST)
    public Result editInfo(@ModelAttribute UserInfoDetail userInfoDetail, HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        LOGGER.info(" sessionPhone:{}", sessionPhone);
        userInfoService.updateUserInfoDetail(sessionPhone, userInfoDetail);
        return success("个人信息已保存");
    }

    @ApiOperation(value = "重置密码")
    @RequestMapping(value = "/password/reset", method = RequestMethod.POST)
    public Result forgetPassword(String phone, String smsCode, String newPassword) {
        boolean isSmsCodeRight = smsService.validateCode(phone, smsCode);
        if (!isSmsCodeRight) {
            return error(" 短信验证码错误 ");
        }
        userInfoService.resetPassword(phone, newPassword);
        return success("密码修改成功");
    }

    //    @RequestMapping("/phone/edit")
    public Result modifyUserPhone(String oldPhone, String smsCode, String newPhone, HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        if (StringUtils.isEmpty(sessionPhone) || !sessionPhone.equals(oldPhone)) {
            return error(" 请确认是本人操作");
        }
        boolean isSmsCodeRight = smsService.validateCode(newPhone, smsCode);
        if (!isSmsCodeRight) {
            return error(" 短信验证码错误 ");
        }
        String token = getToken(request);
        userInfoService.modifyUserPhone(oldPhone, newPhone, token);
        return success("手机号已更改");
    }

    @ApiOperation(value = "上传头像")
    @RequestMapping(value = "/headIcon", method = RequestMethod.POST)
    public Result uploadHeadIcon(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        try {
            String fileName = file.getOriginalFilename();
            String suffix = "";
            if (fileName.lastIndexOf(".") > 0) {
                suffix = fileName.substring(fileName.lastIndexOf("."));
            }
            long currentTime = System.currentTimeMillis();
            String uri = aliOSSService.upload(file.getInputStream(), sessionPhone + "-head-" + currentTime + suffix,
                    headIconBucketName);

            userInfoService.setHeadIcon(uri, sessionPhone);
            return success(uri);
        } catch (IOException e) {
            LOGGER.error("上传头像错误", e);
            return error("上传头像错误");
        }
    }

    @ApiOperation(value = "获取用户等级")
    @RequestMapping(value = "/level", method = RequestMethod.POST)
    public Result getUserLevel(HttpServletRequest request) {
        String sessionPhone = getSessionPhone(request);
        List<UserConfigOutputVo> outputVo = userInfoService.getUserLevel(sessionPhone);
        return success(outputVo);
    }
}
